package com.asktgapp.JGTool;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.asktgapp.application.MyApplication;
import com.asktgapp.modulebase.common.util.LogUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.hyphenate.EMError;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * time:2018/1/22
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class Utils {


    public static void onHxError(int emError) {
        switch (emError) {
            case EMError.MESSAGE_INVALID:
                LogUtil.LogI("emError：消息不合法");
                break;
            case EMError.MESSAGE_SEND_TRAFFIC_LIMIT:
                LogUtil.LogI("emError：消息发送过快，触发限流");
                break;
            case EMError.NETWORK_ERROR:
                LogUtil.LogI("emError：网络异常");
                break;
            case EMError.SERVER_BUSY:
                LogUtil.LogI("emError：服务器繁忙");
                break;
            case EMError.SERVER_NOT_REACHABLE:
                LogUtil.LogI("emError：无法访问到服务器");
                break;
            case EMError.USER_BINDDEVICETOKEN_FAILED:
                LogUtil.LogI("emError：绑定设备token失败");
                break;
            case EMError.USER_LOGIN_ANOTHER_DEVICE:
                LogUtil.LogI("emError：账户在另外一台设备登录");
                break;
            case EMError.USER_NOT_LOGIN:
                LogUtil.LogI("emError：用户未登录");
                break;
            case EMError.MESSAGE_INCLUDE_ILLEGAL_CONTENT:
                LogUtil.LogI("emError：消息内容包含非法或敏感词");
                break;
            case EMError.MESSAGE_ENCRYPTION_ERROR:
                LogUtil.LogI("emError：消息加解密错误");
                break;
            case EMError.INVALID_USER_NAME:
                LogUtil.LogI("emError：用户id不正确");
                break;

        }
        LogUtil.LogI("emError:" + emError);
    }

    /*
     * 判断服务是否启动,context上下文对象 ，className服务的name
     */
    public static boolean isServiceRunning(Context mContext, String className) {

        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);

        if (!(serviceList.size() > 0)) {
            return false;
        }
        Log.e("OnlineService：", className);
        for (int i = 0; i < serviceList.size(); i++) {
            Log.e("serviceName：", serviceList.get(i).service.getClassName());
            if (serviceList.get(i).service.getClassName().contains(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    public static boolean noContainsEmoji(String... strs) {
        for (int j = 0; j < strs.length; j++) {
            String str = strs[j];//真为不含有表情
            int len = str.length();
            for (int i = 0; i < len; i++) {
                if (isEmojiCharacter(str.charAt(i))) {
                    return false;
                }
            }

        }
        return true;
    }

    private boolean check(String string) {
        int len = string.length();
        for (int i = 0; i < len; i++) {
            if (isEmojiCharacter(string.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    public static int D2I(double d) {
        return (new Double(d)).intValue();
    }

    public static String DtS(double b) {
        DecimalFormat df = new DecimalFormat("##########.##");
        return df.format(b);
    }

    public static boolean isForeground(Context context, String className) {
        if (context == null || Util.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            Log.i("top", "top:" + cpn);
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;

    }


    public static String D2S(double arg) {
        if (arg % 1 == 0) {
            return String.valueOf((int) arg);
        } else {
            return String.valueOf(arg);
        }
    }

    public static int dp2px(Context context, int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return (int) ((dp * displayMetrics.density) + 0.5);
    }


    public static String getDeviceId(Context context) {
        String id;

        id = PreferencesUtil.getString(context,"deviceId");
        if(TextUtils.isEmpty(id)){
           id = getDeviceIdForSystem(context);
        }

        return id;
    }
    @SuppressLint("MissingPermission")
    private static String getDeviceIdForSystem(Context context){

        if (!MyApplication.getInstance().READ_PHONE_PERMISSION)
            return "101";
        String id;
        TelephonyManager tm = (TelephonyManager) context.getSystemService(
                Context.TELEPHONY_SERVICE);

        if (tm.getDeviceId() != null) {
            id = tm.getDeviceId();
        } else {
            id = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        PreferencesUtil.putString(context,"deviceId",id);
        return id;
    }

    public static String getDate(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Calendar now = Calendar.getInstance();
        int nowDay = now.get(Calendar.DAY_OF_MONTH);
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        Calendar target = Calendar.getInstance();
        target.setTime(arg);
        Calendar targetDay = Calendar.getInstance();
        int Day = targetDay.get(Calendar.DAY_OF_MONTH);

        if (now.getTimeInMillis() - targetDay.getTimeInMillis() <= (2 * 24 * 60 * 60 * 1000)) {
            //两天之内
            if (nowDay - Day == 0) {
                return Util.DateToStr(arg, "HH:mm");
            } else {
                return "昨天";
            }
        } else {
            return Util.DateToStr(arg, "MM月dd日");
        }
    }

    public static String getDateAll(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        return Util.DateToStr(arg, "yyyy-MM-dd HH:mm:ss");
    }

    public static String getDateHm(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        return Util.DateToStr(arg, "HH:mm");
    }

    public static String getDateMD(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        return Util.DateToStr(arg, "MM-dd");
    }

    public static String getDateYMD(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        return Util.DateToStr(arg, "yyyy-MM-dd");
    }


    public static String getDateYear(String date) {
        if (Util.isEmpty(date)) {
            return " ";
        }
        Date arg = Util.str2Date(date, "yyyy.MM.dd HH:mm:ss");
        return Util.DateToStr(arg, "yyyy");
    }

    public static boolean isFutureDate(String string) {
        if (Util.isEmpty(string)) {
            return false;
        }
        Date date = Util.StrToDate(string, "yyyy-MM-dd");
        Calendar temp = Calendar.getInstance();
        temp.setTime(date);
        Calendar toDay = Calendar.getInstance();
        if (temp.get(Calendar.YEAR) > toDay.get(Calendar.YEAR))//如果年份大则一定是未来时间
        {
            return true;
        } else if (temp.get(Calendar.YEAR) < toDay.get(Calendar.YEAR)) {//如果年份小则一定是过去时间
            return false;
        } else if (temp.get(Calendar.YEAR) == toDay.get(Calendar.YEAR)) {
            if (temp.get(Calendar.MONTH) > toDay.get(Calendar.MONTH))//如果月份大则一定是未来时间
            {
                return true;
            } else if (temp.get(Calendar.MONTH) < toDay.get(Calendar.MONTH)) {//如果月份小则一定是过去时间
                return false;
            } else if (temp.get(Calendar.MONTH) == toDay.get(Calendar.MONTH)) {

                if (temp.get(Calendar.DAY_OF_MONTH) >= toDay.get(Calendar.DAY_OF_MONTH))//如果日期大则一定是未来时间
                {
                    return true;
                } else if (temp.get(Calendar.DAY_OF_MONTH) < toDay.get(Calendar.DAY_OF_MONTH)) {//如果日期小则一定是过去时间
                    return false;
                }
            }

        }
        return false;
    }

    public static boolean isGoneDate(String string) {
        if (Util.isEmpty(string)) {
            return false;
        }
        Date date = Util.StrToDate(string, "yyyy-MM-dd");
        Calendar temp = Calendar.getInstance();
        temp.setTime(date);
        Calendar toDay = Calendar.getInstance();
        if (temp.get(Calendar.YEAR) > toDay.get(Calendar.YEAR))//如果年份大则一定是未来时间
        {
            return false;
        } else if (temp.get(Calendar.YEAR) < toDay.get(Calendar.YEAR)) {//如果年份小则一定是过去时间
            return true;
        } else if (temp.get(Calendar.YEAR) == toDay.get(Calendar.YEAR)) {
            if (temp.get(Calendar.MONTH) > toDay.get(Calendar.MONTH))//如果月份大则一定是未来时间
            {
                return false;
            } else if (temp.get(Calendar.MONTH) < toDay.get(Calendar.MONTH)) {//如果月份小则一定是过去时间
                return true;
            } else if (temp.get(Calendar.MONTH) == toDay.get(Calendar.MONTH)) {

                if (temp.get(Calendar.DAY_OF_MONTH) > toDay.get(Calendar.DAY_OF_MONTH))//如果日期大则一定是未来时间
                {
                    return false;
                } else if (temp.get(Calendar.DAY_OF_MONTH) <= toDay.get(Calendar.DAY_OF_MONTH)) {//如果日期小则一定是过去时间
                    return true;
                }
            }

        }
        return false;
    }

    public static String getDateString(int year, int month, int dayOfMonth) {
        month = month + 1;
        String thismonth;
        String thisday;
        if (month < 10) {
            thismonth = "0" + month;
        } else {
            thismonth = month + "";
        }
        if (dayOfMonth < 10) {
            thisday = "0" + dayOfMonth;
        } else {
            thisday = dayOfMonth + "";
        }
        return year + "-" + thismonth + "-" + thisday;
    }

    public static void sendMessage(Context context, String phone) {
        if (Util.isEmpty(phone))
            return;
        Uri smsToUri = Uri.parse("smsto:" + phone);
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        context.startActivity(intent);
    }

    public static void callPhone(Context context, String phone) {
        if (Util.isEmpty(phone))
            return;
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;

    private static long toSeconds(long date) {
        return date / 1000L;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

    private static long toDays(long date) {
        return toHours(date) / 24L;
    }

    private static long toMonths(long date) {
        return toDays(date) / 30L;
    }

    private static long toYears(long date) {
        return toMonths(date) / 365L;
    }


    /**
     * new Date(long)
     * 根据给定时间显示 时间字符串：几秒前、几分钟前、今天HH:mm、昨天HH:mm、一年之内(MM-dd HH:mm)、yyyy-MM-dd HH:mm
     *
     * @param date
     * @return String
     */
    public static String getAskTime(Date date) {
        if (date == null) {
            return "";
        }
        Date now = new Date();//获取当前时间
        long delta = now.getTime() - date.getTime();
        if (delta < ONE_MINUTE) {
//            long seconds = toSeconds(delta);
            return "刚刚";
        }
        if (delta < ONE_HOUR) {
            long minutes = toMinutes(delta);
            return (minutes <= 0 ? 1 : minutes) + "分钟前";
        }
        if (delta < (ONE_HOUR * 24L)) {
            long hours = toHours(delta);
            return (hours <= 0 ? 1 : hours) + "小时前";
        } else {
            long days = toDays(delta);
            if (days <= 3) {
                return days + "天前";
            } else {
                Calendar cal1 = Calendar.getInstance();
                Calendar cal2 = Calendar.getInstance();
                cal1.setFirstDayOfWeek(Calendar.MONDAY);//西方周日为一周的第一天，咱得将周一设为一周第一天
                cal2.setFirstDayOfWeek(Calendar.MONDAY);
                cal1.setTime(now);
                cal2.setTime(date);
                int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
                if (subYear == 0)// subYear==0,说明是同一年
                {
                    return Util.DateToStr(date, "MM-dd HH:mm");
                } else {
                    return Util.DateToStr(date, "yyyy-MM-dd");
                }

            }
        }
    }

    public static Context getContext() {
        return MyApplication.getInstance();
    }
}
